import axios from 'axios'
import { ElMessage } from 'element-plus'
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  timeout: 20 * 1000 * 15
})

service.interceptors.response.use(response => {
  if (response.config.responseType === 'blob') {
    return response
  }
  if (response.status === 200) {
    addParentProperty(response, null);
    if (!response.data.success) {
      response.data.isSystemError = false;
    }
    return response.data
  } else {
    const data = {
      isSystemError: true,
      success: false,
      message: 'Unexpected status code:' + response.status
    }
    return data;
  }
}, (error) => {
  if (error.response) {
    // 服务器响应了一个状态码，不在 2xx 范围内
    console.error('Error Response:', error.response.data);
    console.error('Error Status:', error.response.status);
    console.error('Error Headers:', error.response.headers);
  } else if (error.request) {
    // 请求已经发出，但没有收到响应
    console.error('No Response Received:', error.request);
  } else {
    // 发送请求时出了点问题
    console.error('Error Message:', error.message);
  }
  console.error('Config:', error.config);
  const data = {
    isSystemError: true,
    success: false,
    message: error.message
  }
  return Promise.resolve(data);
})

function addParentProperty(obj, parent) {
  if (obj === null) return;
  if (obj) console.log(obj.__ndCode)
  if (Array.isArray(obj)) {
    obj.forEach(item => {
      if (typeof item === 'object' && item != null) {
        addParentProperty(item, parent);
      }
    });
    return;
  }
  if (typeof obj === 'object' && "__ndCode" in obj && obj !== null) {
    Object.defineProperty(obj, 'parent', {
      value: parent,
      enumerable: false
    });
  }
  if ("__ndCode" in obj) { parent = obj; } else { parent = null; }
  for (const key in obj) {
    if (obj[key] === null) continue;
    if (typeof obj[key] === 'object') {
      addParentProperty(obj[key], parent);
    }
  }
}

export const promiseCall = (url, data, callback = () => {}) => {
  return new Promise((resolve, reject) => {
    service.post(url,
      data
    ).then(data => {
      if (data.success) {
        callback(data.value)
        resolve(data)
      } else {
        if (data.isSystemError) {
          ElMessage({
            message: data.message + "\n" + (data.detailMessage != null ? data.detailMessage : ''),
            type: 'error',
            plain: true
          })
        } else {
          ElMessage({
            message: data.message + "\n" + (data.detailMessage != null ? data.detailMessage : ''),
            type: 'error',
            plain: true
          })
        }
        resolve({ success: false, message: data.message })
      }
    }).catch(err => {
      resolve({ success: false, message: String(err) })
    })
  })
}

export const promiseCallSilent = (url, data, callback = () => {}) => {
  return new Promise((resolve, reject) => {
    service.post(url,
      data
    ).then(data => {
      if (data.success) {
        callback(data.value)
        resolve(data)
      } else {
        if (data.isSystemError) {
          ElMessage({
            message: data.message + "\n" + data.detailMessage != null ? data.detailMessage : '',
            type: 'error',
            plain: true
          })
        } else {
          // ElMessage({
          //   message: data.message + "\n" + data.detailMessage != null ? data.detailMessage : '',
          //   type: 'error',
          //   plain: true
          // })
        }
        resolve({
          success: false,
          message: data.message
        })
      }
    }).catch(err => {
      resolve({
        success: false,
        message: String(err)
      })
    })
  })
}
